//http://10.10.20.30:8020/oauth/token?client_id=mobile_1&client_secret=secret_1&grant_type=password&username=aa&password=aa
//http://10.10.20.30:8020/file/download?access_token=ab39ef8d794843b0b51938a69db5aafc&robot_type=20&model=1-v1.0&ip=192.168.1.4&robot_id=11019883ECC7A26A341B2E51ACC08131
//http://10.10.20.30:8020/file/download?access_token=ab39ef8d794843b0b51938a69db5aafc&robot_type=20&model=1-v1.1&ip=192.168.1.4&robot_id=11019883ECC7A26A341B2E51ACC08131
//http://10.10.20.30:8020/file/download?access_token=ab39ef8d794843b0b51938a69db5aafc&robot_type=20&model=1-v1.2&ip=192.168.1.4&robot_id=11019883ECC7A26A341B2E51ACC08131

// update.go
package main

import (
	"fmt"
	"io/ioutil"
	"net/http"

	"flag"
	"net/url"
	"ubtJSON"
	"ubtxml"
)

type robot struct {
	robot_type string
	model      string
	ip         string
	robot_id   string
}

type client struct {
	access_token string
	robot
}

func (a *client) Download() error {
	u, err := url.Parse("")

	if err != nil {
		//fmt.Println(err)
		return err
	}

	u.Scheme = "http"
	u.Host = "120.25.57.42:8084"
	u.Path = "upgrade/file/download"

	q := u.Query()
	q.Set("access_token", a.access_token)
	q.Set("robot_type", string(a.robot_type))
	q.Set("model", a.model)
	//q.Set("ip", a.ip)
	q.Set("robot_id", a.robot_id)

	u.RawQuery = q.Encode()
	fmt.Println(u.String())
	resp, err := http.Get(u.String())
	if err != nil {
		return err
	}

	defer resp.Body.Close()
	body1, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err
	}

	fmt.Println(string(body1))

	return nil
}

func httpGet(url string) (body string, err error) {
	//fmt.Println("开始登陆", url)
	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}

	defer resp.Body.Close()
	body1, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return "", err
	}

	return string(body1), nil
}

var (
	robot_type = flag.String("n", "zqd", "robot_name")
	model      = flag.String("m", "1-v1.0", "model_id-v1.0")
	ip         = flag.String("i", "203.166.220.157", "ipv4")
	robot_id   = flag.String("r", "NBA19123ECC7A26A341B2E51ACC08AB2", "robot_id")
)

func main() {
	flag.Parse()
	//fmt.Println("开始")
	Token := ubtxml.LoadToken()
	url := Token.GetUrl()
	fmt.Println(url)
	s, err := httpGet(url)
	if err != nil {
		return
	}
	//fmt.Println(s)
	tJosn := ubtJSON.NewTokenReturns(s)
	//fmt.Println("获得Token", tJosn.AccessToken)

	var cl1 = client{}

	cl1.access_token = tJosn.AccessToken
	cl1.robot_type = *robot_type
	cl1.model = *model
	cl1.ip = *ip
	cl1.robot_id = *robot_id

	cl1.Download()
}
